package com.apobates.jforum2.troll.threads.biz.impl.dao;

import com.apobates.jforum2.troll.threads.biz.dao.TopicConfigDao;
import com.apobates.jforum2.troll.threads.entity.TopicConfig;
import java.util.Optional;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xiaofanku
 * @since 20200513
 */
@Repository
public class TopicConfigDaoImpl implements TopicConfigDao{
    @PersistenceContext
    private EntityManager entityManager;
    private final static Logger logger = LoggerFactory.getLogger(TopicConfigDaoImpl.class);

    @Override
    public Optional<TopicConfig> findOneByTopic(long topicId) {
        try {
            TopicConfig tc = entityManager.createQuery("SELECT tc FROM TopicConfig tc WHERE tc.topicId = ?1", TopicConfig.class).setParameter(1, topicId).getSingleResult();
            return Optional.ofNullable(tc);
        } catch (javax.persistence.NoResultException e) {
            if(logger.isDebugEnabled()){
                logger.debug(e.getMessage(), e);
            }
            return Optional.empty();
        }
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(TopicConfig entity) {
        entityManager.persist(entity);
        entityManager.flush();
    }
    
    @Override
    public Optional<TopicConfig> findOne(Long primaryKey) {
        return Optional.ofNullable(entityManager.find(TopicConfig.class, primaryKey));
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Optional<Boolean> edit(TopicConfig updateEntity) {
        try {
            entityManager.merge(updateEntity);
            return Optional.of(true);
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug(e.getMessage(), e);
            }
            return Optional.empty();
        }
    }
    
    @Override
    public Stream<TopicConfig> findAll() {
        return Stream.empty();
    }
    
    @Override
    public long count() {
        return -1L;
    }
}